<?php
namespace Home\Controller;
use Think\Controller;
use Think\Page;

class PayController extends Controller {
    //支付宝支付
    public function pay(){
        $firstGoodsName = '';//第一个商品名称
        $count = I('count');//应付总金额（商品金额+安装费）

        //接受购物车商品ID,如果存在生成订单
        $cid = I('cid');
        if($cid != '')
        {
            $is_install = I('is_install');//是否安装

            //开启事务
            M()->execute('begin');
            $cid_arr = explode(',',$cid);
            $order_number = time().mt_rand(1000,9999);//生成订单号
            $default_address_id = M('user_address')->where(array('status' => 1,'user_id' =>session('user_id')))->getField('address_id');//获取默认地址

            foreach($cid_arr AS $k => $v)
            {
                $where = array(
                    'user_id' => session('user_id'),
                    'cart_id' => $v
                );

                $goodInfo = M('goods_cart gc')->field('gs.good_id,gs.good_name,gs.price,gs.vip_price,gs.grade,gs.picture,gc.goods_num')
                    ->join('__GOODS__ gs on gs.good_id=gc.goods_id')
                    ->where($where)
                    ->find();

                //获取第一个商品的名称
                if($k == 0){
                    $firstGoodsName = $goodInfo['good_name'];
                }

                //写入订单
                $data['order_number'] = $order_number;
                $data['user_id'] = session('user_id');
                $data['good_id'] = $goodInfo['good_id'];
                $data['good_name'] = $goodInfo['good_name'];
                $data['good_picture'] = $goodInfo['picture'];
                //会员存储会员价，普通用户存储市场价
                if(session('user_vip') == 1)
                {
                    $data['price'] = $goodInfo['vip_price'];
                }else{
                    $data['price'] = $goodInfo['price'];
                }
                $data['num'] = $goodInfo['goods_num'];
                $data['grade'] = $goodInfo['grade'];

                $data['address_id'] = $default_address_id;
                $data['add_time'] = date('Y-m-d H:i:s');
                if($is_install){
                    $data['is_install'] = I('is_install');
                }

                if(I('is_install') == 1)
                {
                    //接受对应的安装费,用install_price拼接商品ID组成
                    $install_price = 'install_price_'.$goodInfo['good_id'];
                    $data['install_price'] = I($install_price);

                    //如果能接收到电工ID,代表选择就近安装
                    if(I('diangongid')){
                        $data['electrician_id'] = I('diangongid');
                        $data['install_type'] = 2;
                        $data['electrician_confirm'] = 0;
                    }else{
                        $data['install_type'] = 1;
                    }
                }

                $data['order_status'] = 0;//待支付
                $addResult = M('order')->add($data);
                if(!$addResult){
                    M()->execute('rollback');
                    $this->error('提交订单失败');
                }
            }
            //删除购物车中的商品
            if(false === M('goods_cart')->where(array('cart_id' => array('in',$cid)))->delete())
            {
                M()->execute('rollback');
                $this->error('提交订单失败');
            }

            //将订单信息写入订单总价表
            $countData['order_number'] = $order_number;
            $countData['order_price'] = $count;
            $countData['count_price'] = $count;
            if(!M('count_price')->add($countData)){
                M()->execute('rollback');
                $this->error('提交订单失败');
            }

            //执行事务
            M()->execute('commit');

            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $order_number;
            //订单名称，必填
            if(count($cid_arr) == 1)
            {
                //证明提交了一种商品
                $proName = $firstGoodsName;//trim($_POST['WIDsubject']);
            }else{
                //证明提交了多种商品
                $proName = $firstGoodsName.'等多件';//trim($_POST['WIDsubject']);
            }
            //付款金额，必填
            $total_amount = $count;//trim($_POST['WIDtotal_amount']);
            //商品描述，可空
            $body = '';//trim($_POST['WIDbody']);
        }
        
        //接受订单里未支付的订单，支付完成并修改其状态
        $on = I('on');//订单编号
        if($on != ''){
            //判断订单商品种类，若为一种，不显示“等多件”
            $good_count = M('order')->where(array('order_number' => $on))->count();
            //查询第一件商品名称
            $firstGoodsName = M('order')->where(array('order_number' => $on))->getField('good_name');

            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $on;

            //订单名称，必填
            if($good_count == 1)
            {
                //证明提交了一种商品
                $proName = $firstGoodsName;//trim($_POST['WIDsubject']);
            }else{
                //证明提交了多种商品
                $proName = $firstGoodsName.'等多件';//trim($_POST['WIDsubject']);
            }

            //付款金额，必填，用修改过的订单总额（后台可能会修改订单总价）
            $count_price = M('count_price')->where(array('order_number'=>$on))->getField('count_price');
            $total_amount = $count_price;//trim($_POST['WIDtotal_amount']);

            //商品描述，可空
            $body = '';//trim($_POST['WIDbody']);

        }

        //调用支付宝支付
        $result =  alipay($out_trade_no,$proName,$total_amount,$body);

        //存入支付记录
//        $model = M('house_order');
//        $data = array(
//            'product_name'=>$proName,
//            'order_num'=>$out_trade_no,
//            'total_amount'=>$total_amount,
//            'description'=>$body,
//            'user_id'=>1,
//            'add_time'=>NOW_TIME,
//            'up_time'=>NOW_TIME
//        );
//        $model->add($data);
        //输出
        echo $result;
    }

    public function notify_url(){
        Vendor('Alipay.pagepay/service/AlipayTradeService');
        $arr=$_POST;
        $config = C('alipay');
        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if($result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号

            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号

            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];

            if($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //查询订单状态及总额
                $status = M('order o')->field('o.order_status,cp.count_price')
                    ->join('__COUNT_PRICE__ cp on cp.order_number=o.order_number')
                    ->where('o.order_number='.$out_trade_no)
                    ->find();
                if($status['order_status'] != 1){ //没做处理
                    //判断订单总额是否一致
                    if($status['count_price'] == $_POST['total_amount']){
                        //修改订单状态
                        $data['order_status'] = 1;
                        $data['pay_time'] = date('Y-m-d H:i:s');
                        M('order')->where('order_number='.$out_trade_no)->save($data);

                        //增加商品销量
                        $order_list = M('order')->field('good_id,num')->where(array('order_number'=>$out_trade_no))->select();
                        foreach($order_list AS $k=>$v){
                            M('goods')->where(array('good_id'=>$v['good_id']))->setInc('sale',$v['num']);
                        }

                        echo "success";		//请不要修改或删除
                    }
                }

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }
            
        }else {
            //验证失败
            echo "fail";	//请不要修改或删除

        }
    }

    /**
     * 微信扫码支付
     */
    public function wechat(){
        //接受购物车商品ID,如果存在生成订单
        $cid = I('cid');
        if($cid != '')
        {
            $is_install = I('is_install');//是否安装
            $money = I('count');         //订单金额

            //开启事务
            M()->execute('begin');
            $cid_arr = explode(',',$cid);
            $order_number = time().mt_rand(1000,9999);//生成订单号
            $default_address_id = M('user_address')->where(array('status' => 1,'user_id' =>session('user_id')))->getField('address_id');//获取默认地址

            foreach($cid_arr AS $k => $v)
            {
                $where = array(
                    'user_id' => session('user_id'),
                    'cart_id' => $v
                );

                $goodInfo = M('goods_cart gc')->field('gs.good_id,gs.good_name,gs.price,gs.vip_price,gs.grade,gs.picture,gc.goods_num')
                    ->join('__GOODS__ gs on gs.good_id=gc.goods_id')
                    ->where($where)
                    ->find();

                //获取第一个商品的名称
                if($k == 0){
                    $firstGoodsName = $goodInfo['good_name'];
                }

                //写入订单
                $data['order_number'] = $order_number;
                $data['user_id'] = session('user_id');
                $data['good_id'] = $goodInfo['good_id'];
                $data['good_name'] = $goodInfo['good_name'];
                $data['good_picture'] = $goodInfo['picture'];
                //会员存储会员价，普通用户存储市场价
                if(session('user_vip') == 1)
                {
                    $data['price'] = $goodInfo['vip_price'];
                }else{
                    $data['price'] = $goodInfo['price'];
                }
                $data['num'] = $goodInfo['goods_num'];
                $data['grade'] = $goodInfo['grade'];

                $data['address_id'] = $default_address_id;
                $data['add_time'] = date('Y-m-d H:i:s');
                if($is_install){
                    $data['is_install'] = I('is_install');
                }

                if(I('is_install') == 1)
                {
                    //接受对应的安装费,用install_price凭借商品ID组成
                    $install_price = 'install_price_'.$goodInfo['good_id'];
                    $data['install_price'] = I($install_price);

                    //如果能接收到电工ID,代表选择就近安装
                    if(I('diangongid')){
                        $data['electrician_id'] = I('diangongid');
                        $data['install_type'] = 2;
                        $data['electrician_confirm'] = 0;
                    }else{
                        $data['install_type'] = 1;
                    }
                }
                $data['order_status'] = 0;//待支付
                $addResult = M('order')->add($data);
                if(!$addResult){
                    M()->execute('rollback');
                    $this->error('提交订单失败');
                }
            }
            //删除购物车中的商品
            if(false === M('goods_cart')->where(array('cart_id' => array('in',$cid)))->delete())
            {
                M()->execute('rollback');
                $this->error('提交订单失败');
            }

            //将订单信息写入订单总价表
            $countData['order_number'] = $order_number;
            $countData['order_price'] = $money;
            $countData['count_price'] = $money;
            if(!M('count_price')->add($countData)){
                M()->execute('rollback');
                $this->error('提交订单失败');
            }

            //执行事务
            M()->execute('commit');

            //订单名称，必填
            if(count($cid_arr) == 1)
            {
                //证明提交了一种商品
                $proName = $firstGoodsName;//trim($_POST['WIDsubject']);
            }else{
                //证明提交了多种商品
                $proName = $firstGoodsName.'等多件';//trim($_POST['WIDsubject']);
            }
            //付款金额，必填
            $total_amount = $money;//trim($_POST['WIDtotal_amount']);
            //商品描述，可空
            $body = '';//trim($_POST['WIDbody']);
        }

        //接受订单里未支付的订单，支付完成并修改其状态
        $on = I('on');//订单编号
        if($on != ''){
            $order_number = $on;  //订单编号

            //判断订单商品种类，若为一种，不显示“等多件”
            $good_count = M('order')->where(array('order_number' => $on))->count();
            //查询第一件商品名称
            $firstGoodsName = M('order')->where(array('order_number' => $on))->getField('good_name');

            //订单名称，必填
            if($good_count == 1)
            {
                //证明提交了一种商品
                $proName = $firstGoodsName;//trim($_POST['WIDsubject']);
            }else{
                //证明提交了多种商品
                $proName = $firstGoodsName.'等多件';//trim($_POST['WIDsubject']);
            }

            //付款金额，必填，用修改过的订单总额（后台可能会修改订单总价）
            $money = M('count_price')->where(array('order_number'=>$on))->getField('count_price');

        }

        $notify_url = "http://www.sx-dengshijie.com/index.php/Home/Pay/notify"; //异步通知地址

        //调用微信支付函数
        $url = wxpay($order_number,$money,$notify_url);
        $this->assign('url',$url);
        $this->assign('order_number',$order_number);
        $this->assign('money',$money);
        $this->assign('proName',$proName);
        $this->display('Index/wechat');

    }
    //生成二维码
    public function code(){
        $url = I('url');
        Vendor('Wxpay.example.phpqrcode.phpqrcode');
        \QRcode::png("$url");
    }

    //支付成功后回调
    public function notify(){
        $xml = $GLOBALS['HTTP_RAW_POST_DATA']; //返回的xml
        $xmlObj=simplexml_load_string($xml,'SimplexmlElement',LIBXML_NOCDATA);
        $xmlArr=json_decode(json_encode($xmlObj),true);
        $out_trade_no=$xmlArr['out_trade_no']; //订单号
        $total_fee=$xmlArr['total_fee']/100; //回调回来的xml文件中金额是以分为单位的
        $result_code=$xmlArr['result_code']; //状态
        if($result_code=='SUCCESS'){ //数据库操作
            $status = M('order o')->field('o.order_status,cp.count_price')
                ->join('__COUNT_PRICE__ cp on cp.order_number=o.order_number')
                ->where('o.order_number='.$out_trade_no)
                ->find();
            if($status['order_status'] != 1){ //没做处理
                //判断订单总额是否一致
                if($status['count_price'] == $total_fee){
                    //修改订单状态
                    $data['order_status'] = 1;
                    $data['pay_time'] = date('Y-m-d H:i:s');
                    M('order')->where('order_number='.$out_trade_no)->save($data);

                    //增加商品销量
                    $order_list = M('order')->field('good_id,num')->where(array('order_number'=>$out_trade_no))->select();
                    foreach($order_list AS $k=>$v){
                        M('goods')->where(array('good_id'=>$v['good_id']))->setInc('sale',$v['num']);
                    }

                    echo 'SUCCESS'; //返回成功给微信端
                }
            }
        }else{ //失败
            echo 'FAIL';
            exit;
        }
    }

    //查询微信支付状态
    public function orderquery(){
        ini_set('date.timezone','Asia/Shanghai');
        error_reporting(E_ERROR);
        Vendor('Wxpay.lib.WxPay#Api');
        Vendor('Wxpay.lib.WxPay#Data');
        Vendor('Wxpay.lib.WxPay#Config');
        Vendor('Wxpay.example.log');

        //初始化日志
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

        if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
            $out_trade_no = $_REQUEST["out_trade_no"];
            $input = new \WxPayOrderQuery();
            $input->SetOut_trade_no($out_trade_no);
            $rult = \WxPayApi::orderQuery($input);

            if($rult['trade_state'] == 'SUCCESS'){
                //支付成功
                echo 1;
            }elseif ($rult['trade_state'] == 'NOTPAY'){
                //未支付
                echo 2;
            }elseif ($rult['trade_state'] == 'CLOSED'){
                //已关闭
                echo 3;
            }elseif ($rult['trade_state'] == 'USERPAYING'){
                //用户支付中
                echo 4;
            }elseif ($rult['trade_state'] == 'PAYERROR'){
                //支付失败
                echo 5;
            }
        }
    }
}